import request from '@/utils/request'
import { OrderProductDTO, CouponDiscountDTO } from '@/type/coupon'

const api_coupons = '/coupons'
const api_user_coupons = '/user-coupons'

export default {
  // 获取发放中的优惠券列表
  getCoupons() {
    return request({
      url: `${api_coupons}/list`,
      method: 'get',
    })
  },

  // 根据优惠券id查询优惠券详情
  getCouponById(id: string) {
    // 改为string类型
    return request({
      url: `${api_coupons}/${id}`,
      method: 'get',
    })
  },

  // 领取优惠券
  receiveCoupon(couponId: string) {
    // 改为string类型
    return request({
      url: `${api_user_coupons}/${couponId}/receive`,
      method: 'post',
    })
  },

  // 兑换优惠券
  redeemCoupon(code: string) {
    return request({
      url: `${api_user_coupons}/${code}/exchange`,
      method: 'post',
    })
  },

  // 分页查询我的优惠券
  getMyCouponsPage(
    pageNo: number,
    pageSize: number,
    status: number,
    isAsc: boolean = false,
    sortBy: string = 'termEndTime',
  ) {
    return request({
      url: `${api_user_coupons}/page`,
      method: 'post',
      data: {
        pageNo,
        pageSize,
        status,
        isAsc,
        sortBy,
      },
    })
  },

  async getBestDealCoupon(products: OrderProductDTO[]) {
    // 转换价格单位，将元转换为分
    const convertedProducts = products.map(product => ({
      productId: product.productId,
      quantity: product.quantity,
      price: Math.round(product.price * 100) // 乘以100，将元转为分
    }));
    
    const response = await request({
      url: `${api_user_coupons}/available`,
      method: 'post',
      data: {
        products: convertedProducts
      }
    })
    // 转换返回的优惠金额，将分转换为元
    if (response.data && response.data.data) {
      const convertedData = response.data.data.map((coupon: CouponDiscountDTO) => ({
        ...coupon,
        discountAmount: coupon.discountAmount // 除以100，将分转为元
      }))
      response.data.data = convertedData
    }
    return response
  },
}